package com.riant.myspring.riant.service;

import com.riant.myspring.spring.BeanPostProcessor;
import com.riant.myspring.spring.Component;
import org.springframework.beans.BeansException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Classname RiantBeanPostProcessor
 * @Description TODO
 * @Date 2021/5/8 22:58
 * @Created by 张斌
 */
@Component
public class RiantBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if (beanName.equals("userService")) {
            System.out.println("初始化前");
            ((UserServiceImpl) bean).setName("riant");
        }
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")) {
            System.out.println("初始化后");
            Object proxyObject=Proxy.newProxyInstance(RiantBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑前");
                    method.invoke(bean,args);
                    System.out.println("代理逻辑后");
                    return null;
                }
            });
            return proxyObject;
        }

        return bean;
    }
}
